package com.zkjd.lingdong.bluetooth

import android.bluetooth.BluetoothDevice
import android.bluetooth.le.ScanFilter
import android.content.Context
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharedFlow

/**
 * 设备状态事件
 */
sealed class DeviceEvent {
    data class Connected(val device: BluetoothDevice) : DeviceEvent()
    data class Disconnected(val device: BluetoothDevice) : DeviceEvent()
    data class ButtonPressed(val device: BluetoothDevice, val keyCode: Byte) : DeviceEvent()
    data class BatteryLevelChanged(val device: BluetoothDevice, val level: Int) : DeviceEvent()
    data class ConnectionFailed(val device: BluetoothDevice, val reason: String) : DeviceEvent()
    data class DeviceReady(val device: BluetoothDevice) : DeviceEvent() // 设备完全准备好（通知已启用）
    data class AuthSuccess(val device: BluetoothDevice) : DeviceEvent() // 设备鉴权成功
    data class AuthFailed(val device: BluetoothDevice, val reason: String) : DeviceEvent() // 设备鉴权失败
    data class SetReadVules(val device: BluetoothDevice, val vules: String) : DeviceEvent() // 设备回传颜色
}

/**
 * 蓝牙扫描状态
 */
sealed class ScanState {
    object NotScanning : ScanState()
    object Scanning : ScanState()
    data class ScanResult(val devices: List<BluetoothDevice>) : ScanState()
    data class ScanFailed(val reason: String) : ScanState()
}

/**
 * 蓝牙管理接口
 */
interface BleManager {
    /**
     * 初始化蓝牙管理器
     */
    fun initialize(context: Context)
    
    /**
     * 开始扫描蓝牙设备
     */
    fun startScan()

    fun startScan2(macAddress: String)
    
    /**
     * 停止扫描蓝牙设备
     */
    fun stopScan()
    
    /**
     * 获取扫描状态Flow
     */
    fun getScanState(): Flow<ScanState>
    
    /**
     * 连接设备
     */
    suspend fun connect(device: BluetoothDevice): Boolean
    
    /**
     * 断开设备连接
     */
    suspend fun disconnect(device: BluetoothDevice): Boolean
    
    /**
     * 获取设备事件Flow
     */
    fun getDeviceEvents(): SharedFlow<DeviceEvent>
    
    /**
     * 设置工作模式下的LED颜色
     */
    suspend fun setWorkingLedColor(device: BluetoothDevice, r: Int, g: Int, b: Int): Boolean
    suspend fun setWorkingLedColor2(device: String, r: Int, g: Int, b: Int): Boolean
    /**
     * 设置重连模式下的LED颜色
     */
    suspend fun setReconnectingLedColor(device: BluetoothDevice, r: Int, g: Int, b: Int): Boolean
    
    /**
     * 设置防误触模式
     */
    suspend fun setAntiMisoperation(device: BluetoothDevice, enabled: Boolean): Boolean
    
    /**
     * 对设备进行鉴权
     * @param device 蓝牙设备
     * @return 鉴权成功返回true，否则返回false
     */
    suspend fun authenticateDevice(device: BluetoothDevice): Boolean

    /**
     * 关闭蓝牙管理器
     */
    fun close()

    /**
     * 下发防误触指令
     */
    suspend fun setPreventAccid(device: String, pA: Int): Boolean


    suspend fun getBleDevices(): List<BluetoothDevice>
    fun stopScan2()
    fun startScan3(filters: MutableList<ScanFilter>)
    fun getScanState2(): Flow<ScanState>
    fun removeDeviceByAddress(targetAddress: String)
}